package router

import (
	"bytes"
	"encoding/json"
	"gitee.com/baizhige/go-server-tempalte/common/client"
	"gitee.com/baizhige/go-server-tempalte/common/log"
	"github.com/gin-gonic/gin"
	"io"
	"os"
)

// 请求体解密  如果有加密的话
func reqBodyDec(traceId string, c *gin.Context, router *Router) error {
	//不需要解密直接结束
	if !router.ReqDec {
		return nil
	}

	encryptReq := &client.EncryptReq{}
	err := c.ShouldBindJSON(encryptReq)
	if err != nil {
		log.ErrorTF(traceId, "EncryptReq read error: %s", err)
		return err
	}

	//通过客户端ID 拿到缓存的通信密钥 然后解密
	reqBts, err := client.Decoder(traceId, encryptReq.Data, c)
	if err != nil {
		log.ErrorTF(traceId, "EncryptReq decrypt error: %s", err)
		return err
	}

	// 放回请求体
	c.Request.Body = io.NopCloser(bytes.NewBuffer([]byte(reqBts)))

	if os.Getenv("SYS_ENV") != "product" && os.Getenv("SYS_ENV") != "dr" {
		log.DebugTF(traceId, "req data dec is :%s", reqBts)
	}
	return nil
}

// 响应加密
func respEnc(traceId string, c *gin.Context, router *Router) error {
	//不需要加密直接结束
	if !router.RespEnc {
		return nil
	}

	response, arr, err := GetResponseEntity(traceId, c)
	if err != nil {
		return err
	}
	if response == nil {
		return nil
	}
	marshal, _ := json.Marshal(response)
	//通过客户端ID 拿到缓存的通信密钥 然后加密
	respStr, err := client.Encrypt(traceId, string(marshal), c)
	if err != nil {
		log.ErrorTF(traceId, "EncryptResp error: %s", err)
		return err
	}

	// 放回响应体
	resp := &EncResp{Encrypted: true, Data: respStr}
	arr[0] = resp

	if os.Getenv("SYS_ENV") != "product" && os.Getenv("SYS_ENV") != "dr" { //TODO
		log.DebugTF(traceId, "resp data enc is :%s", respStr)
	}
	return nil
}
